<!DOCTYPE HTML>
<html lang="zh" xml:th="http://www.thymeleaf.org">
<head>
    <title>物联网设备调试</title>
    <link rel="stylesheet" th:href="@{/statics/bootstrap/4.6.0/bootstrap.min.css}" />
    <script th:src="@{/statics/jquery-1.12.4.min.js}"></script>
    <script th:src="@{/statics/bootstrap/4.6.0/bootstrap.min.js}"></script>
    <script th:src="@{/statics/system/common.js}"></script>
    <link rel="stylesheet" th:href="@{/statics/layui/layui.css}" />
    <script th:src="@{/statics/layui/layui.js}"></script>
    <script th:src="@{/statics/dayjs.min.js}"></script>
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=yes">

</head>

<body>
<div class="layui-container">
    <h3 th:text="${pageName}" class="title">物联网设备调试</h3>
    <div class="notice" style="margin-bottom: 4px;">
        <span th:text="|连接到 ${serverInfo}|"></span>
        <div class="layui-form-item">
            <button onclick="reConnect()" class="layui-btn layui-btn-primary layui-btn-sm">修改订阅</button>
            <button onclick="exportTxT()" class="layui-btn layui-btn-primary layui-btn-sm">导出日志</button>
            <button onclick="closeWebSocket()" class="layui-btn layui-btn-danger layui-btn-sm">关闭连接</button>
        </div>
    </div>
    <input type="hidden" name="token" id="token" th:value="${token}">
    <div class="layui-row layui-col-space10">
        <div class="layui-col-xs12 layui-col-md6">
            <div class="layui-form-item">
                <div class="layui-input-group">
                    <div class="layui-input-split layui-input-prefix">
                        发送Topic
                    </div>
                    <input id="sendTopic" type="text" class="layui-input" th:value="${sendTopic}" />
                </div>
            </div>
        </div>
        <div class="layui-col-xs12 layui-col-md6">
            <div class="layui-form-item">
                <div class="layui-input-group">
                    <div class="layui-input-split layui-input-prefix">
                        接收Topic
                    </div>
                    <input id="receiveTopic" type="text" class="layui-input" th:value="${receiveTopic}" />
                </div>
            </div>
        </div>
    </div>

    <div class="layui-form-item" hidden="hidden">
        <label class="layui-form-label">QoS</label>
        <div class="layui-input-block">
            <input id="qos" min="0" max="2" type="number" class="layui-input" th:value="${qos}" />
        </div>
    </div>

    <div id="table" th:style="${params.size() > 0} ? '' : 'display: none;'">
        <table class="layui-table">
            <tbody>
            <tr th:each="p : ${params}">
                <td>
                    <span name="batch-text" style="color: grey;display: none">
                        批量发送
                    </span>
                    <div class="layui-input-inline" style="width: 100%;display: flex;flex-direction: row;">
                        <span name="batch-text" style="color: grey; display: none;width: 70px;align-self: center">批量发送</span>
                        <textarea name="message1" class="layui-textarea" style="resize: none; overflow: scroll; display: none;" th:text="${p.message}"></textarea>
                        <input name="messageInput" type="text" class="layui-input" style="height: 38px;" th:value="${p.message}" />
                    </div>
                </td>
                <td style="width: 180px">
                    <button style="width: 100%;" onclick="sendOther(this)" class="layui-btn layui-bg-blue layui-btn-primary" type="button" th:text="${p.button}"></button>
                </td>
            </tr>
            </tbody>
        </table>
    </div>
    <div class="layui-input-group">
        <input id="text" type="text" class="layui-input" placeholder="请输入调试信息" style="flex: 1;">
        <button onclick="send()" class="layui-btn layui-btn-primary layui-bg-blue" style="flex: 0 0 90px;">发送</button>
    </div>
    <textarea wrap="off" id="message" class="layui-textarea" disabled ></textarea>

</div>


</body>

<script type="text/javascript">
    document.addEventListener('DOMContentLoaded', initialize);

    let websocket;

    function initialize() {
        const token = $('#token').val();
        const sendTopic = $('#sendTopic').val();
        const receiveTopic = $('#receiveTopic').val();
        const qos = $('#qos').val();

        const sendTopicBase64 = base64encode(sendTopic);
        const receiveTopicBase64 = base64encode(receiveTopic);

        if ('WebSocket' in window) {
            const url = `${getNmqsWebsocket()}/websocket/${token}/${sendTopicBase64}/${receiveTopicBase64}/${qos}`;
            console.log(url);
            initializeWebSocket(url);
        } else {
            alert('您的浏览器不支持WebSocket协议，建议您更换 Chrome 浏览器');
        }

        setupMessageToggles();
    }

    function initializeWebSocket(url) {
        displayMessage("正在连接到远程服务器...");
        websocket = new WebSocket(url);

        websocket.onerror = () => displayMessage("连接失败，请检查服务器是否正常！");
        websocket.onopen = () => displayMessage("开始建立连接");
        websocket.onmessage = event => displayMessage(event.data, "Receive");
        websocket.onclose = () => displayMessage("连接关闭");

        window.onbeforeunload = () => websocket.close();
    }

    function displayMessage(message, type = "System") {
        const prefix = `[${type}][${dayjs().format('HH:mm:ss')}] `;
        setMessageInnerHTML(prefix + message);
    }

    function validateInput(selector, errorMessage) {
        const value = $(selector).val();
        if (!value) {
            alert(errorMessage);
            return false;
        }
        return value;
    }

    function reConnect() {
        const token = validateInput('#token', "Token不能为空！");
        const sendTopic = validateInput('#sendTopic', "发送订阅不能为空！");
        const receiveTopic = validateInput('#receiveTopic', "接收订阅不能为空！");
        const qos = validateInput('#qos', "QoS不正确");

        if (qos < 0 || qos > 2) {
            alert("QoS不正确");
            return;
        }

        if (!sendTopic || !receiveTopic || qos === false) return;

        closeWebSocket();

        setTimeout(() => {
            const sendTopicBase64 = base64encode(sendTopic);
            const receiveTopicBase64 = base64encode(receiveTopic);
            const url = `${getNmqsWebsocket()}/websocket/${token}/${sendTopicBase64}/${receiveTopicBase64}/${qos}`;

            console.log(url);
            initializeWebSocket(url);
        }, 1000);
    }

    function setMessageInnerHTML(innerHTML) {
        const message = $('#message').val();
        const messageArray = message.split('\n');
        if (messageArray.length > 500) {
            messageArray.pop();
        }
        messageArray.unshift(innerHTML);
        $('#message').val(messageArray.join('\n'));
    }

    function closeWebSocket() {
        displayMessage("正在关闭连接...");
        if (websocket) websocket.close();
    }

    function send() {
        const message = $('#text').val();
        if (websocket && message) {
            websocket.send(message);
            displayMessage(message, "Send");
        }
    }

    function sendOther(this1) {
        //获取按钮上面的input的值
        let message = $(this1).parent().parent().find('input');
        let textarea = $(this1).parent().parent().find('textarea');

        // 如果 message 的 display 是 none，说明是 textarea，则批量发送
        if (message.css('display') === 'none') {
            let messageArray = textarea.val().split('\n');

            let i = 0;
            let interval = setInterval(function () {
                if (i < messageArray.length) {
                    try {
                        websocket.send(messageArray[i]);
                        //发送消息后，将消息显示在网页上
                        displayMessage(messageArray[i], "Send");
                        i++;
                    } catch (error) {
                        console.error("发送消息时发生错误:", error);
                        clearInterval(interval); // 发生错误时清除定时器
                    }
                } else {
                    clearInterval(interval); // 确保在发送完所有消息后清除定时器
                }
            }, 100);
        } else {
            try {
                websocket.send(message.val());
                displayMessage(message.val(), "Send");
            } catch (error) {
                console.error("发送消息时发生错误:", error);
            }
        }
    }

    function base64encode(text) {
        return btoa(text).replace(/\//g, "_");
    }

    function setupMessageToggles() {
        const messages = document.getElementsByName('message1');
        const messageInputs = document.getElementsByName('messageInput');
        const batchTexts = document.getElementsByName('batch-text');

        messages.forEach((message, i) => {
            const lines = message.value.split('\n');

            if (lines.length > 1) {
                message.style.display = 'none';
                messageInputs[i].value = lines[0];
                batchTexts[i].style.display = 'none';

                const button = document.createElement('button');
                button.type = 'button';
                button.textContent = '展开';
                button.style.marginLeft = '10px';
                button.classList.add('layui-btn', 'layui-bg-blue', 'layui-btn-primary');
                button.onclick = () => toggleView(button);

                messageInputs[i].parentElement.appendChild(button);
            } else {
                message.style.display = 'none';
                batchTexts[i].style.display = 'none';
            }
        });
    }

    function toggleView(button) {
        const container = button.parentElement;
        const textarea = container.querySelector('textarea');
        const input = container.querySelector('input');
        const batchText = container.querySelector('[name="batch-text"]');

        const isHidden = textarea.style.display === 'none';
        textarea.style.display = isHidden ? 'block' : 'none';
        input.style.display = isHidden ? 'none' : 'block';
        batchText.style.display = isHidden ? 'block' : 'none';
        button.textContent = isHidden ? '收起' : '展开';
    }

    function exportTxT() {
        const message = $('#message').val();
        const blob = new Blob([message], { type: "text/plain;charset=utf-8" });
        saveAs(blob, `mqtt-${dayjs().format('YYYY-MM-DD-HH-mm-ss')}.txt`);
    }

    function saveAs(blob, filename) {
        const url = window.URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = filename;
        a.click();
        window.URL.revokeObjectURL(url);
    }

</script>

<style>
    html, body {
        height: 100%;
        margin: 0;
    }

    .layui-container {
        display: flex;
        flex-direction: column;
        height: 100%;
        box-sizing: border-box;
        padding: 10px;
    }

    #table {
        flex: 1;
        overflow-y: auto;
        margin-bottom: 10px;
        border: 1px solid #f5f6f7;
    }

    #table td {
        padding: 2px;
    }

    textarea {
        width: 100%;
        resize: none;
        height: auto;
        overflow: hidden;
        background-color: #f5f6f7;
        overflow-x: scroll;
    }

    .layui-input-group {
        display: flex;
        align-items: center;
    }

    #message {
        flex: 1;
        margin-bottom: 10px;
        height: auto;
        overflow-y: auto;
    }

    .notice {
        padding: 10px 15px;
        background: #f5f6f7;
        display: flex;
        justify-content: space-between;
        align-items: center;
        border-radius: 15px;
    }

    .notice span {
        color: #666;
        font-size: 16px;
    }

    .notice .layui-form-item {
        margin-bottom: 0;
    }

    .layui-input-split {
        height: 38px;
        line-height: 38px;
        background: #f5f6f7;
    }

</style>
</html>
